<?php

namespace app\api\controller\v1;

use app\common\model\User as UserModel;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use think\Lang;
use think\Db;
use app\common\model\Follower;
use think\Validate;
/**
 * 接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login','userworkshome'];
    protected $noNeedRight = ['userpraised','attention'];
    
    /**
     * [_initialize 初始化]
     * @return [type] [description]
     */
    public function _initialize()
    {
        parent::_initialize();
        $Lang = Lang::load(APP_PATH . 'api/lang/zh-cn/user.php');
    }
     public function login()
    {
        if (!$this->request->isPost()){
            $this->error(__('请求类型错误!'));
        }
        $code=$this->request->param('code');
        if(!$code){
            $this->error('参数无效!');
        }
        $appid = 'wx90e8ac1acbe79bcc';
		$AppSecret = '7eec3104bece4fb42791e9570b965e92';
		$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$AppSecret."&js_code=".$code."&grant_type=authorization_code";
        $str = file_get_contents($url);
        $json = json_decode($str,true);
        // $arr = get_object_vars($json);
        if(isset($json['errcode'])){
            $this->error('登录失败!');
        }
        $openid = $json['openid'];
        $substr = substr($openid,0,7);
        $chaeck = UserModel::where('wxappid',$openid)->find();
        if($chaeck){
            $password = preg_replace('# #', '', $substr);
            $ret = $this->auth->login($chaeck['username'], $password);
            if ($ret) {
                $userinfo = $this->auth->getUserinfo();
                unset($userinfo['id']);
                unset($userinfo['user_id']);
                $data = ['userinfo' => $userinfo];
                $this->success(__('Logged in successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        }else{
            $userData=$this->request->param('userData');
            $jsonStr = @stripslashes(html_entity_decode($userData));
            $jsonArr = @htmlspecialchars_decode($jsonStr, true);
            $json = json_decode($jsonArr,true);
            if(!is_array($json)||!isset($json['nickName'])){
                $this->error('参数无效!');
            }
            $uuid = UserModel::order('id DESC')->field('id')->find();
            if($uuid){
                $username = $uuid->id+config('uniqueuid');
            }else{
                $username = config('uniqueuid');
            }
            $email = '';
            $mobile = '';
            $nickname = isset($json['nickName'])?$json['nickName']:'用户'.mt_rand(1000000000,9999999999);
            $avatarUrl = isset($json['avatarUrl'])?$json['avatarUrl']:'';
            $password = preg_replace('# #', '', $substr);
            $ret = $this->auth->register($username, $password, $email, $mobile, ['nickname' => preg_replace('# #', '', $nickname),'avatar'=>$avatarUrl,'wxappid'=>$openid]);
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                unset($data['userinfo']['id']);
                unset($data['userinfo']['user_id']);
                $this->success(__('Sign up successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        }
	    
    }

    /**
     * Undocumented function
     * 关注,粉丝,点赞统计接口
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-05 18:06:03
     * @return void
     */
    public function userpraised(){
        $userinfo = $this->auth->getUserinfo();
        $userId = $userinfo['id'];
        if(!$userId){
            $this->error('请登录!');
        }
        $whereConcat = '';
        $and = '';
        $key = 'video_id';
        $workscount = Db('video')->where(['user_id'=>$userId,'status'=>1])->field('id')->select();
        if(!$workscount){
            $arr['workscount'] =0;
            $arr['likecount'] = 0;
            $arr['followercount'] = 0;
            $this->success('',$arr);
        }
        foreach($workscount as $val){
            $whereConcat .= $and . "FIND_IN_SET(".$val['id'].", $key)";
            if ($whereConcat != '') {
                $and = ' OR ';
            }
        }
        //$workscounttext =  rtrim($workscounttext, ',');
        $likecount = Db('like')->where($whereConcat)->count();
        $followercount = Db('follower')->where('form_id',$userId)->count();
        $arr['workscount'] =$workscount?count($workscount):0;
        $arr['likecount'] = $likecount;
        $arr['followercount'] = $followercount;
        $this->success('',$arr);
    }

    /**
     * Undocumented function
     * 粉丝列表
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-05 19:06:11
     * @return void
     */
    public function attention(){
        $userinfo = $this->auth->getUserinfo();
        $userId = $userinfo['id'];
        if(!$userId){
            $this->error('请登录!');
        }
        $arr = Follower::where('form_id',$userId)->with('fan')->select();
        foreach($arr as $key=>$val){
            if(!$val['fan']){
                unset($arr[$key]);
            }  
            $arr[$key]['followercount_count'] = Follower::where('form_id',$arr[$key]['fan']['id'])->count();
        }
        $this->success('',array_values($arr));
    }

    /**
     * Undocumented function
     * 用户个人中心
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-05 19:56:10
     * @param integer $id
     * @return void
     */
    public function userworkshome($id=0){
        $islogin = $this->auth->islogin();
        $userId =0;
        if($islogin){
            $userinfo = $this->auth->getUserinfo();
            $userId = $userinfo['id'];
        }
        $user = UserModel::where(['status'=>'normal','id'=>$id])->field('id,username,nickname,avatar,bio,gender')->find();
        if(!$user){
            $this->error('用户不存在!');
        }
        if($user&&$userId){
            $user['follower'] = Follower::where(['user_id'=>$userId,'form_id'=>$user['id']])->find();
            $user['follower']=$user['follower']?1:0;
        }
        $user['followernum'] = Follower::where(['user_id'=>$user['id']])->count();
        $user['attentionnum'] = Follower::where(['form_id'=>$user['id']])->count();
        $this->success('',$user);
    }

}